package com.zgm.ch09.jdbc.jdbcTemplate.update._4_3;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;


public class JdbcTemplateDemo {

	private JdbcTemplate jdbcTemplate;
	
	public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("_4_3-context.xml", JdbcTemplateDemo.class);
        JdbcTemplateDemo demo = (JdbcTemplateDemo) ac.getBean("jdbcTemplateDemo");
        
        demo.runCall();
//        demo.runUpdate();
    }
	
	private void runCall() {
//		this.jdbcTemplate.call(new MyCallableStatementCreator(), null) ; //有问题
		System.out.println(this.jdbcTemplate.call(new MyCallableStatementCreator(), 
				new ArrayList()) + "abd");    //好像也有问题
	}

	private void runUpdate() {
		this.jdbcTemplate.update("update t_customer set first_name = first_name || 'Xx'");
		this.jdbcTemplate.update("delete t_customer where id = ?", new PreparedStatementSetter() {

			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setLong(1, 1002);	
			}
			
		});
		
		this.jdbcTemplate.update("update t_customer set first_name = ? where id = ?", new Object[] {"abcd", 1000}, new int[] {Types.VARCHAR, Types.INTEGER} );
	}
	
	private static class MyCallableStatementCreator implements CallableStatementCreator {

		public CallableStatement createCallableStatement(Connection con)
				throws SQLException {
			
//			CallableStatement cs =  con.prepareCall("? = call f_calculate");
			CallableStatement cs =  con.prepareCall("{? = call f_calculate}");
			cs.registerOutParameter(1, Types.INTEGER);
			
			return cs;
		}
		
	}
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
